const _ = require('lodash');
class Settlement {
    /**
     * 结算，每月末结算(会员卡)
     * @api {GET}         /                       结算，每月末结算(会员卡)
     * @apiName           /
     * @apiGroup          Settlement
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
       }
     */
    async index(ctx) {
        const { db, model } = ctx;

        // 1.查询所有会员用户
        let user = await db.User.findAll({
            where: { isMember: 1 }
        });

        // 2.判断是否过期
        user = ctx.jsonArr(user);
        const nowTime = Math.round(new Date() / 1000);

        for (let i = 0; i < user.length; i++) {
            const changeDay = Math.round(nowTime - user[i].buyMemberTime);

            if (changeDay > user[i].endMemberTime - user[i].buyMemberTime) {
                // ①.查询所有会员用户消费日志
                let transaction;
                try {
                    transaction = await model.transaction();

                    await db.User.update(
                        { isMember: 0 },
                        { where: { id: user[i].id } }
                    );
                    await transaction.commit();
                } catch (e) {
                    console.log(e, '结算失败，请检查。');
                    await transaction.rollback();
                    return;
                }

                let userUse = await db.Use.findAll({
                    where: { userId: user[i].id, type: 3, over: 0 }
                });
                userUse = ctx.jsonArr(userUse);

                // ② 洗的次数除以会员卡总价
                const limitPrice = user[i].member / userUse.length;
                console.log('limitPrice', limitPrice);

                // ③ 查询设备洗车次数
                let a = [];
                for (let j = 0; j < userUse.length; j++) {
                    // 垃圾算法不忍直视 QAQ
                    const count = await db.Use.count({
                        where: {
                            userId: user[i].id,
                            type: 3,
                            merchantId: userUse[j].merchantId
                        }
                    });
                    a.push({ id: userUse[j].merchantId, count: count });
                    // 更新状态
                    let transactions;
                    try {
                        transactions = await model.transaction();
                        await db.Use.update(
                            { over: 1 },
                            { where: { id: userUse[j].id } }
                        );
                        await transactions.commit();
                    } catch (e) {
                        console.log(e, '结算失败，请检查。');
                        await transactions.rollback();
                        return;
                    }
                }
                a = _.uniqBy(a, 'id');
                console.log('a', a);

                // ④ 循环结算
                for (let k = 0; k < a.length; k++) {
                    let merchant = await db.Admin.findOne({
                        where: { id: a[k].id }
                    });
                    const money =
                        parseInt(merchant.money) + limitPrice * a[k].count;
                    console.log('money', money);
                    // 事务
                    let event;
                    try {
                        event = await model.transaction();
                        await db.Admin.update(
                            { money: money },
                            { where: { id: a[k].id } }
                        );
                        await event.commit();
                        console.log('结算成功');
                    } catch (e) {
                        console.log(e, '结算失败，请检查。');
                        await event.rollback();
                        return;
                    }
                }
            } else {
                console.log('暂未结算');
            }
        }
        ctx.success();
    }
    /**
     * 结算，每月末结算(次卡)
     * @api {GET}         /                       结算，每月末结算(次卡)
     * @apiName           /
     * @apiGroup          SettlementCar
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
       }
     */
    async SettlementCar(ctx) {
        const { db, model } = ctx;

        // 1.查询所有次卡用户
        let user = await db.User.findAll({
            where: { isTimeCard: 1 }
        });

        // 2.判断是否过期
        user = ctx.jsonArr(user);
        const nowTime = Math.round(new Date() / 1000);

        for (let i = 0; i < user.length; i++) {
            const changeDay = Math.round(nowTime - user[i].buyCardTime);

            if (changeDay > user[i].endCardTime - user[i].buyCardTime) {
                // ①.查询所有会员用户消费日志
                let transaction;
                try {
                    transaction = await model.transaction();

                    await db.User.update(
                        { isTimeCard: 0 },
                        { where: { id: user[i].id } }
                    );
                    await transaction.commit();
                } catch (e) {
                    console.log(e, '结算失败，请检查。');
                    await transaction.rollback();
                    return;
                }

                let userUse = await db.Use.findAll({
                    where: { userId: user[i].id, type: 2, over: 0 }
                });
                userUse = ctx.jsonArr(userUse);

                // ② 洗的次数除以次卡总价
                const limitPrice = user[i].cardTime / userUse.length;

                console.log('limitPrice', limitPrice);

                // ③ 查询设备洗车次数
                let a = [];
                for (let j = 0; j < userUse.length; j++) {
                    // 垃圾算法不忍直视 QAQ
                    const count = await db.Use.count({
                        where: {
                            userId: user[i].id,
                            type: 2,
                            merchantId: userUse[j].merchantId
                        }
                    });
                    a.push({ id: userUse[j].merchantId, count: count });
                    // 更新状态
                    let transactions;
                    try {
                        transactions = await model.transaction();
                        await db.Use.update(
                            { over: 1 },
                            { where: { id: userUse[j].id } }
                        );
                        await transactions.commit();
                    } catch (e) {
                        console.log(e, '结算失败，请检查。');
                        await transactions.rollback();
                        return;
                    }
                }
                // 驱虫
                a = _.uniqBy(a, 'id');
                console.log('次数', a);
                // ④ 循环结算
                for (let k = 0; k < a.length; k++) {
                    let merchant = await db.Admin.findOne({
                        where: { id: a[k].id }
                    });

                    const money =
                        parseInt(merchant.money) + limitPrice * a[k].count;
                    console.log('分红money', money);

                    // 事务
                    let event;
                    try {
                        event = await model.transaction();
                        await db.Admin.update(
                            { money: money },
                            { where: { id: a[k].id } }
                        );
                        await event.commit();
                        console.log('结算成功');
                    } catch (e) {
                        console.log(e, '结算失败，请检查。');
                        await event.rollback();
                        return;
                    }
                }
            } else {
                console.log('次卡暂未结束');
            }
        }
        ctx.success();
    }
}
module.exports = new Settlement();
